<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ id ? '试题修改' : '试题录入' }}</span>
      </div>

      <!-- 表单区域 -->
      <el-form
        ref="q"
        :model="q"
        :rules="rules"
        label-width="110px"
        class="demo-ruleForm"
      >
        <!-- 学科 -->
        <el-form-item label="学科:" prop="subjectID">
          <el-select
            v-model.number="q.subjectID"
            style="width: 400px"
            placeholder="请选择"
            @change="getCatalogList"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录:" prop="catalogID">
          <el-select
            v-model.number="q.catalogID"
            style="width: 400px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in catalogList"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业:" prop="enterpriseID">
          <el-select
            v-model.number="q.enterpriseID"
            style="width: 400px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市:" prop="province">
          <el-select
            v-model="q.province"
            style="width: 200px"
            placeholder="请选择"
            @change="q.city = ''"
          >
            <el-option
              v-for="(item, index) in provinces"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-select
            v-model="q.city"
            style="width: 195px; margin-left: 5px"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in citys(q.province)"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向:" prop="direction">
          <el-select
            v-model="q.direction"
            style="width: 400px"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型:" prop="questionType">
          <el-radio-group v-model="q.questionType" @input="changeType">
            <el-radio
              v-for="(item, index) in questionType"
              :key="index"
              :label="item.value.toString()"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度:" prop="difficulty">
          <el-radio-group v-model="q.difficulty">
            <el-radio
              v-for="(item, index) in difficulty"
              :key="index"
              :label="item.value.toString()"
            >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干:" prop="question">
          <quill-editor
            v-model="q.question"
            :options="editorOption"
          />
        </el-form-item>
        <!-- 选项 -->
        <el-form-item
          v-if="q.questionType !== '3'"
          v-model="checkbox"
          label="选项"
          prop="radio"
        >
          <!-- 单选框 -->
          <el-radio-group
            v-if="q.questionType === '1'"
            v-model="radioSelect"
            @input="changeTrue"
          >
            <el-row v-for="(item, index) in q.options" :key="index" :gutter="5">
              <el-col :span="0.5">
                <el-radio :label="index">{{ item.code }}:</el-radio>
              </el-col>
              <el-col style="width: 240px">
                <el-input v-model="item.title" />
              </el-col>
              <el-col :span="3">
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  class="upload-demo"
                  multiple
                  :limit="3"
                >
                  <button>
                    上传图片
                    <i class="el-icon-circle-close" />
                  </button>
                </el-upload>
              </el-col>
            </el-row>
          </el-radio-group>
          <!-- 复选框 -->
          <el-checkbox-group
            v-if="q.questionType === '2'"
            v-model="checkbox"
            @change="changeChoice"
          >
            <el-row v-for="(item, index) in q.options" :key="index" :gutter="5">
              <el-col :span="0.5">
                <el-checkbox :label="index">{{ item.code }}:</el-checkbox>
              </el-col>
              <el-col style="width: 240px">
                <el-input v-model="item.title" />
              </el-col>
              <el-col :span="3">
                <el-upload
                  action="https://jsonplaceholder.typicode.com/posts/"
                  class="upload-demo"
                  multiple
                  :limit="3"
                >
                  <button>
                    上传图片
                    <i class="el-icon-circle-close" />
                  </button>
                </el-upload>
              </el-col>
            </el-row>
          </el-checkbox-group>
          <el-row>
            <el-button
              :disabled="q.questionType === '1'"
              type="danger"
              size="small"
              @click="addFormItem"
            >增加选项与答案</el-button>
          </el-row>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频:" prop="videoURL">
          <el-input v-model="q.videoURL" style="width: 400px" />
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item label="答案解析:" prop="answer">
          <quill-editor
            v-model="q.answer"
            :options="editorOption"
          />
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注" prop="remarks">
          <el-input
            v-model="q.remarks"
            type="textarea"
            :rows="4"
            style="width: 400px"
          />
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签:" prop="tags">
          <el-select
            v-model="tags"
            multiple
            style="width: 400px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            :type="id ? 'success' : 'primary'"
            @click="handle"
          >确认{{ id ? '修改' : '提交' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import { simple as getSubjectList } from '@/api/hmmm/subjects'
import { list as getCatalogListDetail } from '@/api/hmmm/directorys'
import { list as getCompanyList } from '@/api/hmmm/companys'
import {
  add as addQuestion,
  detail as getQuestionDetail,
  update as updateQuestionDetail
} from '@/api/hmmm/questions'
import * as location from '@/api/hmmm/citys.js'
import {
  direction,
  questionType,
  difficulty,
  q,
  rules,
  toolbar
} from '@/api/hmmm/constants'
import { simple as getTagsList } from '@/api/hmmm/tags'
export default {
  name: 'Que',
  data() {
    return {
      id: null, // 试题id
      subjectList: [], // 学科列表
      catalogList: [], // 目录列表
      companyList: [], // 企业列表
      provinces: location.provinces(), // 地区
      citys: location.citys, // 选择城市是一个函数,v-for的时候调用它
      radioSelect: null, // 选定单选
      checkbox: [], // 选定多选
      direction, // 方向
      questionType, // 题型
      difficulty, // 难度
      tagsList: [], // 标签列表
      // 富文本编辑器配置选项
      editorOption: {
        modules: {
          toolbar,
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        theme: 'snow',
        placeholder: ''
      },
      // 表单项数据
      q: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          {
            code: 'A', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ], // 选项,
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      rules, // 表单校验规则
      tags: [] // 标签
    }
  },
  created() {
    this.id = +this.$route.query.id
    this.getQuestionDetail()
    this.getSubjectList()
    this.getCompanyList()
    this.getTagsList()
  },
  methods: {
    // 路由跳转到本页面时根据id判断是新增还是修改
    async getQuestionDetail() {
      if (this.id) {
        const { data } = await getQuestionDetail({ id: this.id })
        this.q = data
        const str = data.tags.split(',')
        this.tags = this.tags.concat(str)
        this.radioSelect = data.options.findIndex(item => item.isRight === 1)
        this.q.questionType === '2' &&
					data.options.forEach((item, index) => {
					  item.isRight === 1 && this.checkbox.push(index)
					})
      }
    },
    // 获取学科列表
    async getSubjectList() {
      const { data } = await getSubjectList()
      this.subjectList = data
    },
    // 获取目录列表
    async getCatalogList(val) {
      this.q.catalogID = ''
      if (this.subjectList.length !== 0) {
        const {
          data: { items }
        } = await getCatalogListDetail({ subjectID: val })
        this.catalogList = items
      }
    },
    // 获取企业列表
    async getCompanyList() {
      const {
        data: { items }
      } = await getCompanyList()
      this.companyList = items
    },
    // 获取标签列表
    async getTagsList() {
      const { data } = await getTagsList()
      this.tagsList = data
    },
    // 点击按钮提交或是修改
    handle() {
      this.$refs.q.validate(async ok => {
        if (ok) {
          if (this.id) {
            await updateQuestionDetail({
              id: this.id,
              ...this.q,
              tags: this.tags.join(',')
            })
            this.$message.success('修改数据成功')
          } else {
            this.q.tags = this.tags.join(',')
            await addQuestion(this.q)
            this.$message.success('添加数据成功')
          }
          this.q = q
          this.$refs.q.resetFields()
          this.$router.push('/questions/list')
        }
      })
    },
    // 点击单选框时排他
    changeTrue(val) {
      this.q.options.forEach((item, index) => {
        if (index === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
    },
    // 点击多选框时排他
    changeChoice(val) {
      this.q.options.forEach((item, index) => {
        item.isRight = false
        if (val.includes(index)) {
          item.isRight = true
        }
      })
    },
    // 修改题型时重置数据
    changeType() {
      this.q.options.forEach(item => (item.isRight = false))
      this.radioSelect = null
      this.checkbox = []
    },
    // 增加多选选项
    addFormItem() {
      const code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      const length = this.q.options.length
      if (length <= 8) {
        this.q.options.push({
          code: code.charAt(length), // 代码
          title: '', // 标题
          img: '', // 图片URL
          isRight: false // 是否正确答案
        })
      } else {
        this.$message.warning('选项过多,禁止添加')
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/questions.scss';
</style>
